package pers.smalltown.ourspace.record;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Predeal record exported from liuhen.
 * @author luhha
 *
 */
@Component
public class RecordPreDeal {
	@Autowired
	private OurRecordDao ourRecordDao;
	
	public static void main(String[] args) throws Exception {
		RecordPreDeal test = new RecordPreDeal();
		test.addDataToDB(test.preDeal("WX"));
	}
	private boolean contenting = false;
	private boolean headDealed = false;
	private String platform = "QQ";
	private int contentDealCount = 0;
	private Pattern senderAndTimePattern = Pattern.compile("<p>发送者：(.*)<span class=\"time\">时间：(.*)</span></p>");
	private Pattern imgContentPattern = Pattern.compile("<img class=\"image\" src=\"(.*)\"/>");
	public List<Record> preDeal(String type)  throws Exception {
		String filePath = "C:/Users/luhha/Desktop/maybelast/qq.html";
		if (type.equals("WX")) {
			filePath = "C:/Users/luhha/Desktop/maybelast/wechat.html";
		}
		this.platform = filePath.endsWith("qq.html") ? "QQ" : "WX";
		FileReader fileReader = new FileReader(new File(filePath));
		BufferedReader reader = new BufferedReader(fileReader);
		String content = "";
		
		List<Record> result = new ArrayList<Record>();
		Record temp = null;
		for (int i = 0; ; i++) {
			content = reader.readLine();
			if (content == null) {
				break;
			}
			if (contentBegin(content)) {
				contenting = true;
				temp = new Record();
				result.add(temp);
				continue;
			}
			if (contentEnd(content)) {
				contenting = false;
				headDealed = false;
				contentDealCount = 0;
				
				temp.setPlatform(platform);
				//System.out.println("content:" + temp);
				temp = null;
				continue;
			}
			
			if (contenting) {
				dealContent(content, temp);
			}
		}
		reader.close();
		return result;
	}
	public void deal(String platform) throws Exception {
		addDataToDB(preDeal(platform));
	}
	private boolean contentBegin(String content) {
		return content.startsWith("<div class=\"item\">");
	}
	private boolean contentEnd(String content) {
		return content.startsWith("</div>");
	}
	private void dealContent(String content, Record record) {
		if (!headDealed) {
			headDealed = true;
			Matcher senderAndTimeMatcher = senderAndTimePattern.matcher(content);
			if (senderAndTimeMatcher.matches()) {
				record.setSender(senderAndTimeMatcher.group(1));
				record.setDatetime(platform.equals("QQ") ? senderAndTimeMatcher.group(2) : senderAndTimeMatcher.group(2).replaceAll("/", "-"));
			}
			return;
		} else {
			if (content.startsWith("<hr ")) {
				return;
			}
			content = content.replace("<p class=\"content\">", "");
			content = content.replace("</p>", "");
			if (content.contains("<img")) {
				Matcher imgMatcher = imgContentPattern.matcher(content);
				if (imgMatcher.matches()) {
					record.setContent(imgMatcher.group(1));
				} else {
					record.setContent(content);
				}
			} else {
				record.setContent(record.getContent() != null ? record.getContent() + content : content);
			}
		}
	}
	private void addDataToDB(List<Record> recordList) {
		System.out.println("Prepare add to db.");
		List<Record> oldData = new ArrayList<>();
		List<Record> needJustData = new ArrayList<>();
		for (int i = 0; i < recordList.size(); i++) {
			Record temp = recordList.get(i);
			int compareResult = temp.getDatetime().compareTo("2021-03-08 23:59:59");
			if (compareResult <= 0) {
				oldData.add(temp);
				recordList.remove(i);
				if (temp.getDatetime().compareTo("2021-03-08 00:00:00") >= 0) {
					needJustData.add(temp);
					recordList.remove(i);
				}
			} else {
				break;
			}
		}
		
		dealJustData(needJustData);
		
		System.out.println("准备插入新数据...");
		List<Record> batch = new ArrayList<>();
		for (int i = 0; i < recordList.size(); i++) {
			if (i > 0 && i % 500 == 0) {
				ourRecordDao.insertBatch(batch);
				System.out.println("已插入 500 条");
				batch.clear();
			}
			batch.add(recordList.get(i));
		}
		int num = ourRecordDao.insertBatch(batch);
		System.out.println("已插入" + num + "条");
		System.out.println("完成!");
	}
	/**
	 * 处理需要比对的数据（即临界日期的数据）
	 * @param needJustData
	 */
	private void dealJustData(List<Record> needJustData) {
		List<Record> newData = new ArrayList<>();
		for (int i = 0; i < needJustData.size(); i++) {
			Record oneRecord = needJustData.get(i);
			if (ourRecordDao.judgeExist(oneRecord) == null) {
				newData.add(oneRecord);
			}
		}
		System.out.println("临界日期有新数据共:" + newData.size());
		if (newData.size() > 0) {
			ourRecordDao.insertBatch(newData);
		}
	}
}
